<template>
  <view class="padding-top">
    <view class="addr radius-4" @tap="selectAddress">
      <view class="w-100 flex bg-white p-20 border-box b-r-10">
        <view class="icon">
          <u-icon name="map" color="#ECA52B" size="28"></u-icon>
        </view>
        <view class="right" v-if="addressInfo.receiveId">
          <view class="tel-name">
            <view class="name">{{ addressInfo.receiveName }}</view>
            <view class="tel">{{ $dealTel(addressInfo.receiveMobile) }}</view>
          </view>
          <view class="addres margin-top-xs">
            {{ addressInfo.receiveProvince }}{{ addressInfo.receiveCity || ""
            }}{{ addressInfo.receiveArea || ""
            }}{{ addressInfo.receiveAddress }}
          </view>
        </view>
        <view class="right font-28 flex flex-col-center" v-else
          >点击添加收货地址</view
        >
        <u-icon name="arrow-right" size="18" class="m-t-4"></u-icon>
      </view>
    </view>
    <!-- 购买商品列表 -->
    <view class="buy-list radius-4">
      <view class="row">
        <view
          class="goods-info p-b-10"
          v-for="(item, index) in detail"
          :key="index"
        >
          <view class="img">
            <image :src="item.pic"></image>
          </view>
          <view
            class="flex flex-1 flex-direction justify-between margin-left-sm"
          >
            <view class="text-cut2 font-28">{{ item.productName }}</view>
            <view
              class="text-grey flex justify-between m-t-10 m-b-10 line-h-40"
            >
              <view class="border-box">规格：</view>
              <view class="m-l-10 flex-1 font-24 text-grey">{{
                item.specValue
              }}</view>
            </view>
            <view class="text-grey flex justify-between">
              <view class="price font-28 line-h-60"
                >￥{{ item.platformPrice }}</view
              >
              <u-number-box
                v-model="item.buyCount"
                @change="numChange($event, item)"
                :min="1"
              ></u-number-box>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="blck radius-4">
      <view class="select">备注信息:</view>
      <view class="content">
        <textarea
          class="textarea"
          v-model="remark"
          placeholder="请输入"
          style="padding: 10rpx 0"
          maxlength="100"
          auto-height="20"
        />
      </view>
    </view>

    <view class="p-20 border-box radius-4" v-if="couponList.length">
      <view
        class="w-100 flex justify-between flex-col-center bg-white p-30 border-box b-r-10"
      >
        <view class="font-28">优惠券</view>
        <view class="flex color-g" @click="toCoupon">
          <p class="m-t-4 font-24 m-r-10" v-if="!chooeseCoupon.money">去选择</p>
          <p class="m-t-4 font-32 font-b color-r m-r-10" v-else>
            <span class="font-24">-</span>{{ chooeseCoupon.money
            }}<span class="font-24">元</span>
          </p>
          <u-icon
            name="arrow-right"
            size="18"
            color="#ccc"
            class="m-t-4"
          ></u-icon>
        </view>
      </view>
    </view>

    <view class="footer">
      <view class="w-100 settlement flex justify-between">
        <view class="sum flex"
          >合计:
          <view class="money m-l-10"
            >￥{{ totalPayMoney | calcCouponMoney(chooeseCoupon) }}</view
          >
        </view>
        <view class="btn" @tap="toPay">去支付</view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from "vuex";
import { createOrderFromCart } from "@/common/api/shoppingCart.js";
import { createOrder } from "@/common/api/product.js";
import { receiveList } from "@/common/api/customer.js";
import { Debounce } from "@/common/utils/tools.js";
import AseetsChooese from "./components/aseets.vue";
import { lastVersion } from "@/common/api/api.js";
import { exchangeCouponList } from "@/common/api/xyc.js";
export default {
  components: {
    AseetsChooese,
  },
  data() {
    return {
      totalPayMoney: 0,

      productId: "",
      detail: [],
      remark: "",
      addressInfo: {},
      areaId: "",
      num: 1,
      orderDetailData: {},
      activeIndex: 1,
      calcTotal: 0,
      type: null,
      // 手机运营
      agreement: false,
      operateList: [{ name: "是" }, { name: "否" }],
      couponList: [], //优惠券列表
      chooeseCoupon: {}, //选的优惠券
    };
  },
  computed: {
    ...mapState("user", ["userInfo"]),
  },
  filters: {
    calcCouponMoney: function (e, obj) {
      let money = 0;
      if (obj.money) {
        money = (Number(e) - Number(obj.money)).toFixed(2);
      } else {
        money = Number(e);
      }
      return money;
    },
  },
  onLoad(options) {
    uni.removeStorageSync("selectCoupon");
    this.getAddressList();
    // 放在监听前面
    uni.$on("selectAddressInfo", (res) => {
      this.addressInfo = res;
    });
    uni.$on("selectCoupon", (res) => {
      this.chooeseCoupon = uni.getStorageSync("selectCoupon");
    });
    if (options.type) {
      this.type = options.type;
    }
  },
  onShow() {
    this.getCouponList();
    this.detail = uni.getStorageSync("skuGoodsInfo") || [];
    if (this.detail.length > 0) {
      let totalPayMoney = 0;
      this.detail.forEach((item) => {
        totalPayMoney = (
          Number(totalPayMoney) +
          Number(item.buyCount) * Number(item.platformPrice)
        ).toFixed(2);
      });
      this.totalPayMoney = totalPayMoney;
    }
  },
  onUnload() {
    uni.$off("selectAddressInfo");
  },
  methods: {
    // 判断是否有优惠券
    getCouponList() {
      let data = {
        pageNo: 1,
        pageSize: 10,
        status: 0,
      };
      exchangeCouponList(data).then((res) => {
        if (res.code === 200) {
          this.couponList = res.data || [];
        }
      });
    },
    // 购买件数更改
    numChange(val, data) {
      let num = val.value;
      let list = JSON.parse(JSON.stringify(this.detail));
      let totalPayMoney = 0;
      list.forEach((item) => {
        if (data.cartId == item.cartId) {
          item.buyCount = num;
        }
        totalPayMoney = (
          Number(totalPayMoney) +
          Number(item.buyCount) * Number(item.platformPrice)
        ).toFixed(2);
      });
      this.detail = list;
      uni.setStorageSync("skuGoodsInfo", this.detail);
      this.totalPayMoney = totalPayMoney;
    },
    // 提交订单
    toPay: Debounce(function (e) {
      uni.setStorageSync("payAlipay", false);
      uni.setStorageSync("payWechat", false);
      if (!this.addressInfo.receiveId) {
        return this.$msg("请添加收货地址");
      }
      if (this.type == "cart") {
        let arr = [];
        this.detail.forEach((item) => {
          let obj = {
            cardId: item.cartId,
            buyCount: item.buyCount,
          };
          arr.push(obj);
        });
        let data = {
          receiveId: this.addressInfo.receiveId,
          remark: this.remark,
          shopCartInfo: arr,
          couponId: this.chooeseCoupon.couponId,
        };
        createOrderFromCart(data).then((res) => {
          if (res.code == 200) {
            uni.navigateTo({
              url:
                "/pages/order/payOrder?orderId=" +
                res.data.outOrderId +
                "&productId=" +
                this.detail[0].productId +
                "&moneyTotal=" +
                res.data.payAmount,
            });
          }
        });
      } else {
        uni.showLoading({
          title: "订单提交中",
          mask: true,
        });
        let parmas = {
          skuId: this.detail[0].id,
          receiveId: this.addressInfo.receiveId,
          remark: this.remark,
          buyCount: this.detail[0].buyCount,
          couponId: this.chooeseCoupon.couponId,
        };
        createOrder(parmas)
          .then((res) => {
            uni.hideLoading();
            if (res.code == 200) {
              uni.navigateTo({
                url:
                  "/pages/order/payOrder?orderId=" +
                  res.data.outOrderId +
                  "&productId=" +
                  this.detail[0].productId +
                  "&moneyTotal=" +
                  res.data.payAmount,
              });
            } else {
              this.$msg(res.msg);
            }
            console.log("res", res);
          })
          .catch((err) => {
            uni.hideLoading();
          });
      }
    }, 800),
    toCoupon() {
      uni.navigateTo({
        url: "/pages/order/couponList?totalPayMoney=" + this.totalPayMoney,
      });
    },
    // 跳转地址列表
    selectAddress() {
      uni.navigateTo({
        url: "/pages/my/address/addressList",
      });
    },
    //地址列表
    getAddressList() {
      receiveList().then((res) => {
        if (res.data.length > 0) {
          res.data.filter((item) => {
            if (item.defaultFlag) {
              this.addressInfo = item;
            }
          });
        }
      });
    },
    // 判断app版本号
    getServerNo(version, isPrompt = false, callback) {
      let bool = false;
      lastVersion(1).then((res) => {
        let data = {
          versionCode: res.data.versionCode,
        };
        let that = this;
        plus.runtime.getProperty(plus.runtime.appid, function (inf) {
          if (data.versionCode == inf.versionCode) {
            bool = true;
          } else {
            bool = false;
          }
        });
      });
      return bool;
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #f2f2f2;
}
</style>
<style lang="scss" scoped>
.addr {
  width: 100%;
  padding: 20upx 20rpx 0;
  .icon {
    width: 80upx;
    height: 80upx;
    display: flex;
    align-items: center;
    image {
      width: 60upx;
      height: 60upx;
    }
  }

  .tel-name {
    width: 100%;
    display: flex;
    font-size: 32upx;

    .tel {
      margin-left: 40upx;
    }
  }

  .addres {
    width: 100%;
    font-size: 26upx;
    color: #999;
  }

  .right {
    width: 77%;
  }
}

.buy-list {
  margin: 20rpx;
  .row {
    .goods-info {
      padding: 20rpx;
      background-color: #fff;
      width: 100%;
      display: flex;
      border-bottom: 2rpx solid #f3f3f3;

      .img {
        width: 22vw;
        height: 22vw;
        border-radius: 10upx;
        overflow: hidden;
        flex-shrink: 0;
        margin-right: 10upx;

        image {
          width: 22vw;
          height: 22vw;
        }
      }
      .price {
        color: #f06c7a;
      }
      .info {
        width: 100%;
        height: 22vw;
        overflow: hidden;
        display: flex;
        flex-wrap: wrap;
        position: relative;

        .title {
          width: 100%;
          font-size: 28upx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }

        .spec {
          font-size: 22upx;
          background-color: #f3f3f3;
          color: #a7a7a7;
          height: 36upx;
          display: flex;
          align-items: center;
          padding: 0 10upx;
          border-radius: 20upx;
          margin-bottom: 20vw;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          overflow: hidden;
        }
      }
    }
    .goods-info:first-child {
      border-radius: 10rpx 10rpx 0 0;
    }
    .goods-info:last-child {
      border: none;
      border-radius: 0rpx 0rpx 10rpx 10rpx;
    }
  }
}

.order {
  width: 92%;
  padding: 10upx 4%;
  margin: 30upx auto 20upx auto;
  background-color: #fff;

  .row {
    margin: 20upx 0;
    height: 40upx;
    display: flex;

    .left {
      font-size: 28upx;
    }

    .right {
      margin-left: 40upx;
      font-size: 26upx;
      color: #999;

      input {
        font-size: 26upx;
        color: #999;
      }
    }
  }
}

.blck {
  margin: 20rpx;
  color: #232323;
  font-size: 28rpx;
  padding: 31rpx 31rpx 0;
  box-sizing: border-box;
  background-color: #ffffff;
  margin-bottom: 20rpx;
  padding-bottom: 40upx;

  .select {
    padding-bottom: 23rpx;
  }

  .row {
    width: 100%;
    height: 100upx;
    display: flex;
    align-items: center;

    .left {
      width: 100upx;
      flex-shrink: 0;
      display: flex;
      align-items: center;

      image {
        width: 80upx;
        height: 80upx;
      }
    }

    .center {
      width: 100%;
      font-size: 30upx;
    }

    .tips {
      display: flex;
      flex-direction: column;

      .tip {
        font-size: 24rpx;
        color: #726f6f;
      }
    }

    .right {
      width: 100upx;
      flex-shrink: 0;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.footer {
  width: 100%;
  padding: 0 4%;
  background-color: #fbfbfb;
  height: 100upx;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  font-size: 28upx;
  position: fixed;
  bottom: 0upx;
  z-index: 5;

  .settlement {
    align-items: center;
    .sum {
      font-size: 28upx;
      display: flex;
      justify-content: flex-end;
      .money {
        color: #eca52b;
        font-weight: 600;
      }
    }

    .btn {
      padding: 0 50upx;
      height: 80upx;
      line-height: 80upx;
      background: #eca52b;
      color: #ffffff;
      border: 1px solid #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 30upx;
      border-radius: 40upx;
    }
  }
}
</style>
<style>
.textarea {
  font-size: 26rpx !important;
}
</style>
